var year;
var month;

$(function() {
	var date = new Date();
	var currentYear = date.getFullYear();
	var month = date.getMonth()+1;
	$("#month_id").val(month);
	$("#year").val(currentYear);
	$('#year').datetimepicker({
		startView: 4,
		minView:4,
		autoclose : true,
		format : 'yyyy'
	});
	initDatas();
});

function changeYear() {
	var year = $("#year").val();
	selectYear([{
		name:'year',
		value:year
	}]);
}

var Echart3NormalPie = function(chartid) {
	var title = "";
	var myChart = echarts.init(document.getElementById(chartid));
	var legendLabels = [];
	var dataNameValues = [];

	var getOption = function() {
		return {
			title : {
				text : title
			},
			tooltip : {
				trigger : 'item',
				formatter : "{a} <br/>{b} : {c} ({d}%)"
			},
	         toolbox: {
	                show: true,
	                iconStyle:{
             		normal:{},
             		emphasis:{}
             	},
	                feature: {
	                    dataView: {
	                    	  show: true,
	                    	readOnly: false,
	                    	optionToContent:function(opt){
	                    		  var series = opt.series;
		                    		var coldata1 = [];
		                    		var coldatas = [];
		                    		for(var j=0;j<series[0].data.length;j++){
		                    	        coldata1.push(series[0].data[j].name);
		                    		}
		                    		for(var j=0;j<series.length;j++){
		                    		    var ser = series[j];
		                    		    var col = [];
		                    		    for(var i=0;i<ser.data.length;i++){
		                    		        col.push(ser.data[i].value);
		                    		    }
		                    		    coldatas.push(col);
		                    		}
		                    	    var table = '<table border="1" style="width:100%;text-align:center"><tbody><tr>'
		                    	               + '<td>'+'</td>' ;
		                    	    for(var j=0;j<series.length;j++){
		                    	    	if(series[j].name){
		                    	    		table = table + '<td>' + series[j].name + '</td>';
		                    	    	}else{
		                    	    		table = table + '<td>'+" "+'</td>';
		                    	    	}
		                    	    }
		                    	    for (var i = 0, l = coldata1.length; i < l; i++) {
		                    	        table += '<tr>'
		                    	                 + '<td>' + coldata1[i] + '</td>';
		                    	        for(var z=0;z<coldatas.length;z++){
		                    	        	if(isNaN(parseInt(coldatas[z][i]))){
		                    	        		table = table + '<td>' + '</td>';
		                    	        	}else{
		                    	        		table = table + '<td>' + coldatas[z][i] + '</td>';
		                    	        	}
		                    	        }
		                    	    }
		                    	    table += '</tbody></table>';
		                    	    return table;
	                    	},
	                    	iconStyle:{
	                    		normal:{},
	                    		emphasis:{}
	                    	}
	                    },
	                    saveAsImage: {
	                    	iconStyle:{
	                    		normal:{},
	                    		emphasis:{}
	                    	}
	                    }
	                }
	            },
			legend : {
				orient : 'vertical',
				left : 'left',
				data : legendLabels
			},
			series : [ {
				name : '',
				type : 'pie',
				label:{
					normal:{
						show:true,
		                formatter: "{b}:{d}%",
						textStyle:{}
					}
			    },
				radius : '55%',
				center : [ '50%', '60%' ],
				data : dataNameValues,
				itemStyle : {
					emphasis : {
						shadowBlur : 10,
						shadowOffsetX : 0,
						shadowColor : 'rgba(0, 0, 0, 0.5)'
					}
				}
			} ]
		};
	};
	this.setTitle = function(name) {
		title = name;
	};
	this.setLegendLabels = function(datas) {
		legendLabels = datas;
	};
	this.setDataNameValues = function(datas) {
		dataNameValues = datas;
	};
	this.addDataNameValue = function(pname, pvalue) {
		dataNameValues.push({
			value : pvalue,
			name : pname
		});
	};
	this.show = function() {
		myChart.setOption(getOption());
	};
	this.getChart = function() {
		return myChart;
	};
};

var Bars = function(chartid) {
	var colors = [ '#5793f3', '#008B8B', '#675bba' ];
	var myChart = echarts.init(document.getElementById(chartid));
	var option = {
		dataZoom : [ {
			id : 'dataZoomX',
			type : 'inside',
			show : true,
			xAxisIndex : [ 0 ],
			filterMode : 'filter'
		} ],
		title : {},
		tooltip : {
			trigger : 'axis'
		},
		toolbox : {
			feature : {
				dataView : {
					readOnly : false,
					  show: true,
					optionToContent : function(opt) {
						var axisData = opt.xAxis[0].data;
						var series = opt.series;
						var table = '<table border="1" style="width:100%;text-align:center"><tbody><tr>'
								+ '<td>' + opt.xAxis[0].name + '</td>';
						for ( var j = 0; j < series.length; j++) {
							table = table + '<td>' + series[j].name + '</td>';
						}
						for ( var i = 0, l = axisData.length; i < l; i++) {
							table += '<tr>' + '<td>' + axisData[i] + '</td>';
							for ( var z = 0; z < series.length; z++) {
								if (isNaN(parseInt(series[z].data[i]))) {
									table = table + '<td>' + '</td>';
								} else {
									table = table + '<td>' + series[z].data[i]
											+ '</td>';
								}
							}
						}
						table += '</tbody></table>';
						return table;
					},
					iconStyle : {
						normal : {},
						emphasis : {}
					}
				},
				restore : {
					show : true
				},
				saveAsImage : {
					show : true
				}
			}
		},
		grid : {
			containLabel : true
		},
		legend : {
			data : ['完成率','计划数','实际完成数']
		},
		xAxis : [ {
			type : 'category',
			axisTick : {
				alignWithLabel : true
			},
			data : []
		} ],
		yAxis : [ {
			type : 'value',
			name : '完成率',
			min : 0,
			max : 100,
			position : 'right',
			axisLabel : {
				formatter : '{value}%'
			}
		}, {
			type : 'value',
			name : '数量',
			min : 0,
			
			position : 'left'
		} ],
		series : [ {
			name : '完成率',
			type : 'line',
			data : []
		}, {
			name : '计划数',
			type : 'bar',
			yAxisIndex : 1,
			data : [],
			label:{
				normal:{
					show:true,
					textStyle:{},
					position:'top'
				},
				emphasis:{
					show:true,
					textStyle:{}
				}
			},
			 itemStyle:{
                 normal:{color:'#7ECF51'}
             }
		}, {
			name : '实际完成数',
			type : 'bar',
			yAxisIndex : 1,
			data : [],
			label:{
				normal:{
					show:true,
					textStyle:{},
					position:'top'
				},
				emphasis:{
					show:true,
					textStyle:{}
				}
			},
			 itemStyle:{
                 normal:{color:'#6495ED'}
             }
		} ]
	};
	this.show = function() {
		myChart.setOption(option);
	};
	this.getChart = function() {
		return myChart;
	};
	this.setRatio = function(datas) {
		option.series[0].data = datas;
	};
	this.setMeasures = function(datas) {
		option.series[1].data = datas;
	};
	this.setComplete = function(datas) {
		option.series[2].data = datas;
	};
	this.setXdatas = function(datas) {
		option.xAxis[0].data = datas;
	};
};

function initDatas(){
	year=$("#year").val();
	month=$("#month_id").val();
	$.getJSON("/rest/check/getMonthCheckPlans/"+year+"_"+month, function(result) {
		if(month != "全年"){
			month = month+"月";
		}
		initYearDatas(result,year,month);
	});
}

function refresh() {
	var date = new Date();
	year = date.getFullYear();  
    month = date.getMonth()+1;
    $.getJSON("/rest/check/getMonthCheckPlans/"+year+"_"+month, function(result) {
		if(month != "全年"){
			month = month+"月";
		}
		initYearDatas(result,year,month);
	});
}

function initYearDatas(result,year,month){
	var checkpie = new Echart3NormalPie("checkpie");
	var linebars = new Bars("checkbar");
	var ratiobar =new CategoryBar("ratiobar");
	var linebarname=year+"年度"+month+"南方电网年度保护设备定检计划完成情况";
	$("#linebarid").text(linebarname);
	var piename=year+"年度"+month+"定检完成数";
	$("#pieid").text(piename);
	var rationame=year+"年度"+month+"定检计划完成率";
	$("#barid").text(rationame);
	var ob = result[0];
	if(typeof(ob) == "undefined") {
		$("#checkpie").html("该时间暂无数据信息");
		$("#checkbar").html("该时间暂无数据信息");
		$("#ratiobar").html("该时间暂无数据信息");
	} else {
		var val = ob.value;
		if(val.length===0) {
			$("#checkpie").html("该时间暂无数据信息");
			$("#checkbar").html("该时间暂无数据信息");
			$("#ratiobar").html("该时间暂无数据信息");
		} else {
			ratiobar.setColors(['#76916F']);
			var areas = [];
			var piedatas = [];
			var allplans = [];
			var completes = [];
			var firstobj = result[0];
			for ( var i in firstobj.value) {
				var pieobj = {
						value : '',
						name : ''
				};
				areas.push(firstobj.value[i].name);
				var type = firstobj.value[i].value;
				for ( var j in type) {		
					if (type[j].name == "计划数") {
						allplans.push(type[j].value);
					}
					if (type[j].name == "实际完成数") {
						completes.push(type[j].value);
						pieobj.value = type[j].value;
						pieobj.name = firstobj.value[i].name;
						piedatas.push(pieobj);
					}
				}
			}
			// 完成率
			var ratios = [];
			for ( var i = 0; allplans.length > i; i++) {
				var ratio = (parseInt(completes[i]) / parseInt(allplans[i]))*100;
				ratios.push(ratio.toFixed(2));
			}
			linebars.setRatio(ratios);
			linebars.setMeasures(allplans);
			linebars.setComplete(completes);
			linebars.setXdatas(areas);
			linebars.show();
			for ( var j in piedatas) {
				checkpie.addDataNameValue(piedatas[j].name, piedatas[j].value);
			}
			checkpie.setLegendLabels(areas);
			checkpie.show();
			ratiobar.setxAxis(areas);
			ratiobar.setyAxis(ratios);
			var opt=ratiobar.getOption();
			opt.yAxis[0].axisLabel.formatter='{value}%';
			ratiobar.show();
		}
	}
}
